<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;

$this->title = 'query';
?>
<style>
	body{margin:0;padding:0;}
	.box-header{border-top:3px solid #3c8dbc;border-bottom:1px solid #ddd;}
	.box-header .box-title{font-size:20px;padding-left:10px;}
	.box-body{padding:10px;}
	.btn-info{width:200px;float:right;}
	ul,li{margin:0;padding:0;list-style: none;}
	.search_box{display:none;}
	.search_box .zhezhao{position:fixed;top:0;left:0;right:0;bottom:0;background:#000;opacity:0.6;}
	.search_box .search_form{position:absolute;top:10%;width:60%;background:#FFF;left:20%;}
	.search_box .search_form .form-group{margin-right: 0;margin-left:0;}
	.searchsex_box{overflow:hidden;}
	.searchsex_box>span{float:left;margin-top:10px;font-weight:700;}
	.searchsex_box .radio{float:left;margin-left:50px;}
	.search_form .box-footer{text-align:center;}
	.search_form .box-footer button{width:200px;}
	#dateSelector select{height:30px;line-height:30px;padding:0 5px;border:1px solid #999;border-radius:3px;outline:none;display:inline-block;vertical-align: middle;}
	#dateSelector .checkbox label{display:inline-block;width:30%;font-weight:normal;}
	.box.box-danger{border:none;}
	.box-danger{background:#ecf0f5;}
</style>
<div class="box-success">
	<div class="box-header">
		<h3 class="box-title">统计图</h3>
		<button class="btn btn-block btn-info search_btn">统计条件</button>
	</div>
	<div class="box-body">
		<div class="chart">
			<canvas id="barChart" style="height:230px"></canvas>
		</div>
	</div>
</div>
<div class="box box-danger">
	 <div class="box-body shanxing">
	  	<canvas id="pieChart" style="height:250px"></canvas>
	 </div>
</div>
<!-- 查询条件 -->
<div class="search_box">
  <div class="zhezhao"></div>
  <div class="search_form">
  <div class="box-body">
	<div id="dateSelector">
		<label>统计类型</label>
		<select name="type" class="form-control type">
			<option value="count" selected>按数量查询</option>
			<option value="fee">按金额查询</option>
		</select>
		<label>年</label>
		<select id="idYear" name="year" class="form-control"></select>
		<label>月</label>
		<select id="idMonth" name="month" data="12" class="form-control"></select>
		<label>日</label>
		<select id="idDay" name="day" data="1" class="form-control"></select>
		<div class="form-group check_dep">
      <label>部门</label>
      <div style="overflow:hidden;">
        <div class="checkbox">
          <?php foreach ($department as $key => $val):?>
            <label><input class="department" name="department" type="checkbox" value="<?= $key?>"><?= $val?></label>
          <?php endforeach;?>
        </div>
      </div>
    </div>
		<div class="form-group check_staff">
      <label>员工</label>
      <div style="overflow:hidden;">
        <div class="checkbox">
        </div>
      </div>
    </div>
		<div class="form-group check_limit">
			<label>商品选择</label>
			<div style="overflow:hidden;">
				<div class="checkbox">
					<?php foreach ($product as $key => $val):?>
						<label><input class="product" name="product" type="checkbox" value="<?= $key?>"><?= $val?></label>
					<?php endforeach;?>
				</div>
			</div>
		</div>
	</div>
  </div>
  <div class="box-footer">
  <?= Html::submitButton('提交',['class'=>'btn btn-primary btn-submit']);?>
  <input class="btn btn-warning btn-close" readonly value="关闭" style="width:200px" />
  </div>
  </div>
</div>
<!-- js documents -->
<script type="text/javascript" src="js/jquery.js"></script>
<script src="plugins/Chart.min.js"></script>
<script type="text/javascript" src="plugins/date.js" ></script>
<script type="text/javascript" src="plugins/iscroll.js" ></script>
<script src="plugins/jquery.scs.min.js"></script>
<script src="plugins/CNAddrArr.min.js"></script>
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<script>
    $(".search_btn").click(function(){
      $(".search_box").show();
    });
    $(".search_box .zhezhao").click(function(){
      $(this).parent(".search_box").hide();
    });
    $(".btn-close").click(function(){
      $(".search_box").hide();
    });
    $(".btn-submit").click(function(){
		$(".search_box").hide();
    });

	/*选择部门和部门员工*/
	$(".check_dep input").click(function(){
		var dep = [];
		$('input[name="department"]:checked').each(function(){
		   dep.push($(this).val());
		});
		var url = "<?= Url::toRoute('statistic/getemployee')?>";
	    var _csrf ="<?= Yii::$app->request->getCsrfToken()?>";
		$.ajax({
	      url:url,
	      type:'GET',
	      dataType:'json',
	      data: {"_csrf":_csrf,"dep":dep},
	      success: function(json){
	        var html="";
	        if (json.flag) {
				$.each(json.data,function(index,val){
					html+=' <label><input class="staff" name="employee" type="checkbox" value="'+index+'">'+val+'</label>';
				});
	        }
			$(".check_staff .checkbox").html(html);
	      },
	      error:function(){
	        console.log('网络忙');
	      }
	    });
	});
	var barChartOptions = {
		scaleBeginAtZero: true,
		scaleShowGridLines: true,
		scaleGridLineColor: "rgba(0,0,0,.05)",
		scaleGridLineWidth: 1,
		scaleShowHorizontalLines: true,
		scaleShowVerticalLines: true,
		barShowStroke: false,
		barStrokeWidth: 2,
		barValueSpacing: 5,
		barDatasetSpacing: 1,
		responsive: true,
		maintainAspectRatio: false
	};
	function graph(data) {
		$(".chart").html("");
		var html="<canvas id='barChart' style='height:230px'></canvas>";
		$(".chart").html(html);
		var shuju=[];
		var day;
		$.each(data,function(index,val){
		 shuju[index]={};
		 shuju[index].label=val.name;
		 shuju[index].fillColor=val.color;
		 var arr=[];
		 day=[];
		 $.each(val.data,function(n,v){
		  arr.push(v);
		  day.push(n);
		 })
		 shuju[index].data=arr;
		 arr=[];
		});
		var areaChartData={};
		areaChartData.labels= day;
		areaChartData.datasets=shuju;
		var barChartCanvas = $("#barChart").get(0).getContext("2d");
		var barChart = new Chart(barChartCanvas);
		var barChartData = areaChartData;
		barChartOptions.datasetFill = false;
		barChart.Bar(barChartData, barChartOptions);
	}

	(function ($) {
		var a1=false;
		var a2=false;
		//SELECT控件设置函数
		function setSelectControl(oSelect, iStart, iLength, iIndex) {
			oSelect.empty();
			for (var i = 0; i < iLength; i++) {
				oSelect.append("<option value='" + (parseInt(iStart) + i) + "'>" + (parseInt(iStart) + i) + "</option>");
			}
		}
		$.fn.DateSelector = function (options) {
			options = options || {};
			//初始化
			this._options = {
				ctlYearId: null,
				ctlMonthId: null,
				ctlDayId: null,
				defYear: 0,
				defMonth: 0,
				defDay: 0,
				minYear: 1882,
				maxYear: new Date().getFullYear()
			}
			for (var property in options) {
				this._options[property] = options[property];
			}
			this.yearValueId = $("#" + this._options.ctlYearId);
			this.monthValueId = $("#" + this._options.ctlMonthId);
			this.dayValueId = $("#" + this._options.ctlDayId);
			var dt = new Date(),
					iMonth = parseInt(this.monthValueId.attr("data") || this._options.defMonth),
					iDay = parseInt(this.dayValueId.attr("data") || this._options.defDay),
					iMinYear = parseInt(this._options.minYear),
					iMaxYear = parseInt(this._options.maxYear);
			this.Year = parseInt(this.yearValueId.attr("data") || this._options.defYear) || dt.getFullYear();
			this.Month = 1 <= iMonth && iMonth <= 12 ? iMonth : dt.getMonth() + 1;
			this.Day = iDay > 0 ? iDay : dt.getDate();
			this.minYear = iMinYear && iMinYear < this.Year ? iMinYear : this.Year;
			this.maxYear = iMaxYear && iMaxYear > this.Year ? iMaxYear : this.Year;
			//设置年
			setSelectControl(this.yearValueId, this.minYear, this.maxYear - this.minYear + 1, this.Year);
			$("#idYear").prepend("<option value='' selected>请选择查询年</option>");
			//设置月
			$("#idMonth").html("<option value='' selected>请选择查询月</option>");
			//设置日
			var daysInMonth = new Date(this.Year, this.Month, 0).getDate(); //获取指定年月的当月天数[new Date(year, month, 0).getDate()]
			if (this.Day > daysInMonth) { this.Day = daysInMonth; };
			$("#idDay").html("<option value='' selected>请选择查询日</option>");
			var oThis = this;
			//绑定控件事件
			this.yearValueId.change(function (){
				oThis.Year = $(this).val();
				setSelectControl(oThis.monthValueId, 1, 12, oThis.Month);
				$("#idMonth").prepend("<option value='' selected>请选择查询月</option>");
				oThis.monthValueId.change();
				$("#idDay").html("<option value='' selected>请选择查询日</option>");
			});
			this.monthValueId.change(function(){
				oThis.Month = $(this).val();
				var daysInMonth = new Date(oThis.Year, oThis.Month, 0).getDate();
				if (oThis.Day > daysInMonth) { oThis.Day = daysInMonth; };
				setSelectControl(oThis.dayValueId, 1, daysInMonth, oThis.Day);
				$("#idDay").prepend("<option value='' selected>请选择查询日</option>");
			});
			this.dayValueId.change(function () {
				oThis.Day = $(this).val();
			});
		}
	})(jQuery);

	var myDate = new Date();
	$("#dateSelector").DateSelector({
		ctlYearId: 'idYear',
		ctlMonthId: 'idMonth',
		ctlDayId: 'idDay',
		defYear: myDate.getFullYear(),
		defMonth: (myDate.getMonth()+1),
		defDay: myDate.getDate(),
		minYear: 2016,
		maxYear: myDate.getFullYear()
	});

	$("#idMonth").click(function(){
		if(	$("#idYear").val()==0){
			a1=false;
			$("#idMonth").html("<option value='' selected>请选择查询月</option>");
			$(".warning").html("请先选择年");
		}else{
			a1=true;
			$(".warning").html("");
		}
	});
	$("#idDay").click(function(){
		if(	$("#idYear").val()==0 || $("#idMonth").val()==0){
			a2=false;
			$("#idDay").html("<option value='' selected>请选择查询日</option>");
			$(".warning").html("请先选择年和月份");
		}else{
			a2=true;
			$(".warning").html("");
		}
	});
	$(".btn-submit").click(function(){
		var year = $("#idYear").val();
		var month = $("#idMonth").val();
		var chk_value = [];
		$('input[name="product"]:checked').each(function(){
		   chk_value.push($(this).val());
		});
		var department = [];
		$('input[name="department"]:checked').each(function(){
		   department.push($(this).val());
		});
		var employee = [];
		$('input[name="employee"]:checked').each(function(){
		   employee.push($(this).val());
		});
		var type = $(".type").find("option:selected").val();
		var day = $("#idDay").val();
		var url = "<?= Url::toRoute('statistic/statistic')?>";
	    var _csrf ="<?= Yii::$app->request->getCsrfToken()?>";
	    if (year && !month) {
		    $.ajax({
		      url:url,
		      type:'GET',
		      dataType:'json',
		      data: {
		        year:year,
		        month:month,
		        product:chk_value,
		        day:day,
		        department:department,
		        employee:employee,
		        type:type,
		        _csrf:_csrf
		      },
		      success: function(json){
		      	var numberList = [];
	            $.each(json.data, function (n, value) {
	            	numberList.push(value);
	            });
	            graph(json.data);
	            shanxing(json.data);
		      },
		      error:function(){
		        alert('网络忙');
		      }
		    });
		}
		if (month) {
		    $.ajax({
		      url:url,
		      type:'GET',
		      dataType:'json',
		      data: {
		        year:year,
		        month:month,
		        product:chk_value,
		        day:day,
		        department:department,
		        employee:employee,
		        type:type,
		        _csrf:_csrf
		      },
		      success: function(json){
	            graph(json.data);
	            shanxing(json.data);
		      },
		      error:function(){
		        alert('网络忙');
		      }
		    });
		}    
	});

	/*扇形图*/
	var pieOptions = {
	  segmentShowStroke: true,
	  segmentStrokeWidth: 2,
	  percentageInnerCutout: 50,
	  animationSteps: 100,
	  animationEasing: "easeOutBounce",
	  animateRotate: true,
	  animateScale: false,
	  responsive: true,
	  maintainAspectRatio: false
 	};
	function shanxing(data){
		$(".shanxing").html("");
		var html="<canvas id='pieChart' style='height:250px'></canvas>";
		$(".shanxing").html(html);
		 var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
		 var pieChart = new Chart(pieChartCanvas);
		var shanData=[];
		var day;
		$.each(data,function(index,val){
		 shanData[index]={};
		 shanData[index].label=val.name;
		 shanData[index].color=val.color;
		 var count=0;
		 day=[];
		 $.each(val.data,function(n,v){
		  count+=v;
		  day.push(n);
		 })
		 shanData[index].value=count;
		 count=0;
		});
		var PieData=shanData;
		 pieChart.Doughnut(PieData, pieOptions);
	}
 
</script>
